
<script setup>
	
	import c_exam from './components/exam.vue';
	import xOftenPlay from './components/often.vue';
	import c_reac_text from './components/reac_text.vue';
	import xTortoisePlay from './components/tortoise.vue';
	import { ref, reactive, computed, getCurrentInstance } from 'vue';	
	import { getExerDetail_api, getArticleDetail_api, getArticleWordsList_api, postStartExer_api, postSaveAnswer_api, postSubmitExer_api, postWordJoin_api } from '@/common/apis/course';
	
	
	/** props */
	const props = defineProps(['articleId', 'exerciseId', 'startId', 'analyze']);
	
	
	/** 练习详情 */
	const info = ref({});
	
	/** 文章详情 */
	const detail = ref({});
	
	/** 词汇列表 */
	const wordlist = ref([]);
	
	/** 获取练习详情方法 */
	const getInfo = async () => {
		console.log(props);
		const result = await getExerDetail_api({ id: props.exerciseId, userId: 0 });
		info.value = result;
		detail.value = await getArticleDetail_api({ id: props.articleId, terminal: 'applet' });
		await joinSucces();
	};
	
	async function joinSucces() {
		wordlist.value = arrayObjects.value = await getArticleWordsList_api({ articleId: props.articleId })
	};
	
	/** 获取练习详情 */
	getInfo();
	
	
	const reactextRef = ref({});
	const reactextStatus = ref(false);
	function switchStatus() {
		reactextStatus.value = !reactextStatus.value;
		reactextRef.value?.forEach?.(item => item?.changeStatus?.());
	};
	
	const templist = ref([]);
	const arrayObjects = ref([]);
	const isInArray = data => {
		const inArrayObjects = arrayObjects.value.some(obj => obj.word === data) && reactextStatus.value;
		const inTempList = templist.value.some(obj => obj.word === data);
	    return inArrayObjects || inTempList;
	};
	
	
	const isselect = ref(props.analyze);
	const submitData = reactive({
		logId: 0,
		answers: [],
		exerciseId: props.exerciseId
	});
	
	
	let timer = null;
	const ExamRef = ref({});
	const timeElapsed = ref(0);
	const formattedTime = computed(() => {
	    const minutes = Math.floor(timeElapsed.value / 60)
	    const seconds = timeElapsed.value % 60
	    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
	})
	
	async function handleSubmit(data) {
		if (timeElapsed.value < 60) {
			uni.$fui.toast('60秒之内不能提交答案，请再检查检查吧~');
			return;
		};
		
	    clearInterval(timer);
	    submitData.answers = data;
	    await postSaveAnswer_api(submitData);
	    await postSubmitExer_api({ ...submitData, ...{ useTime: timeElapsed.value, userId: 0 }});
		
		uni.redirectTo({
			url: `/pages/course/word-string/result?examId=${submitData.exerciseId}`
		});
	};
	
	const countup = () => {
	    timeElapsed.value += 1;
	};
	
	async function handleStart() {
		if (!detail.value.questions?.length) {
			uni.$fui.toast('暂无题目~');
			return;
		};
		
		if(!isselect.value) {
			const { logId } = await postStartExer_api(props);
			submitData.logId = logId;
		};
		
		ExamRef.value.open();
		if(!timer) {
			timer = setInterval(countup, 1000);
		};
	};
	
	
	function goMark() {
		if (!wordlist.value?.length) {
			uni.$fui.toast('请先加入生词哦~');
			return;
		};
		
		uni.navigateTo({
			url: `/pages/course/word-string/mark?articleId=${props.articleId}`
		});
	};
	
	
	/** 上传点击的位置 */
	const lastClickIndex = ref(-1);
	
	/** 关闭上次播放状态 */
	const closePlayStatus = () => {
		if (tankStatus.value) {
			tankStatus.value = false;
			templist.value.pop();
		};
		
		reactextRef.value?.forEach?.(item => item?.dianji?.());
		if (!!~lastClickIndex.value) {
			detail.value.sentence[lastClickIndex.value].playType = 0;
		};
	};
	
	/** 音频自然播放结束事件 */
	uni.useAudio.onEnded(closePlayStatus)
	
	/** 点击词串时 */
	const handleClick = (item, index) => {
		closePlayStatus();
		if (!!~lastClickIndex.value && lastClickIndex.value !== index) delete detail.value.sentence[lastClickIndex.value].click;
		item.click = item.click ? item.click + 1 : 1;
		// if (item.click === 4) delete item.click;
		if (item.click === 3) delete item.click;
		lastClickIndex.value = index;
		playType(item, index, 1);
	};
	
	/** 播放不同的类型的音频 */
	const playType = (item, index, type) => {
		closePlayStatus();
		if (item.playType === type) {
			item.playType = 0;
			return;
		};
		
		// uni.useAudio.src(item.personVoiceFile?.[type === 1 ? 'normalVoice' : 'lowSpeedVoice']?.url);
		uni.useAudio.src(item.voiceFile);
		item.playType = type;
		lastClickIndex.value = index;
	};
	
	
	const tankStatus = ref(false);
	const { proxy } = getCurrentInstance();
	const axes = reactive({
		x: 0,
		y: 0
	});
	const currentVal = reactive({
		word: '',
		index: 0,
		parentIndex: 0
	});
	function longpressEvent(word, index, parentIndex, events){
		if(templist.value.length){
			templist.value = [];
		};
		
		currentVal.word = word;
		currentVal.parentIndex = parentIndex;
		currentVal.index = index;
		templist.value.push({ word, indexs: index, parentIndex });
		
		
		let sys = uni.getSystemInfoSync();
		setTimeout(() => {
			// #ifdef APP
			const query = uni.createSelectorQuery().in();
			// #endif
			
			// #ifdef MP-WEIXIN
			const query = uni.createSelectorQuery().in(proxy);
			// #endif
			
			query.select('.tankbox').boundingClientRect(data => {
				if (data) {
					const width = data.width;
					
					// #ifdef APP
					const {pageX, pageY} = events.touches[0];
					axes.x = (sys.screenWidth - pageX) > width ? pageX : (pageX - width);
					axes.y = pageY;
					// #endif
					
					// #ifdef MP-WEIXIN
					const {x, y} = events.detail;
					axes.x = (sys.screenWidth - x) > width ? x : (x - width);
					axes.y = y;
					// #endif
					
					tankStatus.value = true;
				};
			}).exec();
		});
	};
	async function joinEvent() {
		const { word, parentIndex, index } = currentVal;
		arrayObjects.value.push({ word, indexs: index, parentIndex });
		await postWordJoin_api({ articleId: props.articleId, word });
		templist.value = [];
		uni.showToast({
			title: '加入成功',
			icon: 'success'
		});
		
		tankStatus.value = false;
		await joinSucces();
	};
	
	
	/** 跟读测评 */
	const onFollowTest = () => {
		uni.setStorageSync('sentencelist', detail.value.sentence);
		uni.$fui.href('/pages/course/common/spokenlist', { id: props.startId });
	};
	
	
</script>

<template>
	<view class="containerbox bg-white">
		<uv-navbar :title="detail.course?.name" auto-back placeholder />
		
		<view class="py-20 px-30">
			<view class="text-30 text-bold"><text class="text-gray">关卡{{ detail.sort }}：</text>{{ detail.title }}</view>
			<view class="flex items-center text-26 mt-20">
				<view class="text-qgray">参考时长 {{ detail.duration }}''</view>
				<view class="flex items-center ml-20">
					<view class="mr-15 text-qgray">难度系数</view>
					<view class="">
						<uni-icons type="star-filled" v-for="item, index in 5" :key="index" :color="detail.difficultyRate <  item ? '#bababa' : '#f69b2c'" />
					</view>
				</view>
			</view>
			<view class="text-20 text-qgray mt-10 flex items-center"><uni-icons type="info-filled" size="24rpx" color="#a6a5a7" class="mt-5" /> 长按可加入生词表</view>
		</view>
		
		
		<scroll-view scroll-y class="containerbox relative px-30 pt-20">
			<view 
				:key="index" 
				@tap="handleClick(item, index)"
				v-for="item, index in detail.sentence" 
				:class="{ 'actived-item': lastClickIndex === index }"
				class="bg-e8ebff rd-12 mb-30 pl-30 py-30 text-36 flex relative pr-70"
			>
				<!-- template v-if="item.click === 3">
					<view v-for="sentence, i in item.words" :key="`${index}_${i}`" class="text-center w-fit mr-20">
						<view class="text-20">【{{ sentence.phonetic }}】</view>
						<view class="text-30 py-10" @longpress="longpressEvent(sentence.original, i, index, $event)">
							<text :class="{ actived: isInArray(sentence.original) }">{{ sentence.original }}</text>
						</view>
						<view class="text-20">{{ sentence.translation }}</view>
					</view>
				</template> -->
				
				<!-- <view v-else> -->
				<view>
					<c_reac_text :text="item.sentence" :articleId="articleId" ref="reactextRef" @callback="joinSucces" :key="index" />
					<view class="text-20 mt-10" v-if="item.click === 2">{{ item.translate }}</view>
				</view>
				
				
				<view class="absolute flex top-0 right-30 h-100 items-center" @tap.stop>
					<uv-transition :show="!!item.playType">
						<view class="mp3icon">
							<view class="item"></view>
							<view class="item"></view>
							<view class="item"></view>
							<view class="item"></view>
						</view>
					</uv-transition>
					<!-- <view class="transition-opacity" hover-class="opacity-30" @tap="playType(item, index, 1)">
						<x-often-play :color="lastClickIndex === index ? '#fff' : '#fc5507'" :play="item.playType === 1" />
					</view>
					
					<view class="transition-opacity" hover-class="opacity-30" @tap="playType(item, index, 2)">
						<x-tortoise-play :color="lastClickIndex === index ? '#fff' : '#fc5507'" :play="item.playType === 2" />
					</view> -->
				</view>
			</view>
		</scroll-view>
		
		
		<view class="flex items-center justify-between bottombox">
			<view class="btn" :class="{ 'bgc-warning': !reactextStatus, 'bgc-primary': reactextStatus}" @tap="switchStatus">{{ !reactextStatus ? '生词' : '隐藏' }}</view>
			<view class="btn bgc-primary" @tap="goMark" >
				识记<template v-if="wordlist.length">({{ wordlist.length }})</template>
			</view>
			<view class="btn bgc-primary" @tap="handleStart">{{ isselect ? '查看解析' : '做题' }}</view>
			
			<!-- <view class="btn bgc-primary" @tap="onFollowTest">跟读测评</view> -->
		</view>
		
		<audio />
		
		
		<uni-popup ref="ExamRef" type="bottom" borderRadius="10px 10px 10px 10px" backgroundColor="#fff">
			<view class="bgc-white">
				<view class="relative">
					<view class="text-32 text-center py-20">题目列表</view>
					<view class="time flex items-center" v-if="!isselect">
						<image class="timeicon mr-10" :src="`${$imageBaseUrl}course/time.png`" />
						{{ formattedTime }}
					</view>
				</view>
				
				<c_exam :list="detail.questions" @submit="handleSubmit" :read="isselect" :useranswerlist="info.log?.answer"/>
			</view>
		</uni-popup>
		
		
		<view class="tankbox" :class="{ show: tankStatus }" :style="'top:'+(tankStatus ? axes.y : -99999)+'px; left: '+ (tankStatus ? axes.x : -99999) + 'px'">
			<view class="word text-34">{{ currentVal.word }}</view>
			<view class="btn" @click="joinEvent">+ 加入生词</view>
		</view>
	</view>
</template>


<style lang="scss" scoped>
.shadow{box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.07)}
.b-transparent{border-color: transparent}
.bottombox{padding: 20rpx 32rpx}
.btn{height: 80rpx;border-radius: 12rpx;flex: 1;text-align: center;line-height: 80rpx;color: #fff;font-size: 28rpx;display: flex;align-items: center;justify-content: center;position: relative}
.btn+.btn{margin-left: 20rpx}	
.time{position: absolute;right: 20rpx;top: 20rpx}
.timeicon{width: 30rpx;height: 30rpx}
.actived{background-color: $primary;color: #fff}
.tankbox{position: fixed;background-color: #fff; border-radius: 12rpx;box-shadow: 0 0 10rpx rgba(0,0,0,0.5);padding: 0 30rpx;opacity: 0;z-index: 10071}
.tankbox .word{font-weight: 600;padding: 20rpx 0;border-bottom: 1px solid #f0f2f4}
.tankbox .btn{text-align: center;padding: 20rpx 0;color: #0b9aff;font-size: 28rpx}
.tankbox.show{opacity: 1}
.actived-item{background-color: $theme2;color: #fff}
.mp3icon{display:flex;flex-flow:rownowrap;align-items:center;justify-content:space-between;width:30rpx;margin-left:20rpx}
.mp3icon .item{width:4rpx;height:14rpx;background-color:#fff}
.selected .mp3icon .item{background-color:#fff}
.mp3icon .item:nth-of-type(1){animation: grow 1s -0.45s ease-in-out infinite}
.mp3icon .item:nth-of-type(2){animation: grow 1s -0.3s ease-in-out infinite}
.mp3icon .item:nth-of-type(3){animation: grow 1s -0.15s ease-in-out infinite}
.mp3icon .item:nth-of-type(4){animation: grow 1s ease-in-out infinite}
@keyframes grow {
  0%,
  100%{transform: scaleY(1)}
  50%{transform: scaleY(2)}
}
</style>